<?php


namespace app\admin\controller;


use app\admin\conf\Page;
use app\common\model\Config;
use app\common\model\ConvertGoods;
use app\common\model\Given;
use app\common\model\Plugin;
use app\common\model\Region;
use app\common\model\Shipping;
use app\common\model\ShippingArea;
use app\common\model\TabBar;
use app\common\util\AdminException;
use think\db\Builder;
use think\db\Query;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Request;
use think\facade\View;

class System extends Base
{
    public function index()
    {
        $group_list = [
            'basic'    => '基本设置',
            'rate'     => '奖励设置',
            'cash'     => '提现设置',
            //            'recharge'  => '充值设置',
            'given'    => '转赠设置',
            //            'change'     => '转化设置',
            //            'ship'       => '快递设置',
            'sms'      => '短信设置',
            'shopping' => '购物设置',
            'link_list' => '链接管理',
        ];
        View::assign('group_list', $group_list);
        $inc_type = input('inc_type', 'basic');
        View::assign('inc_type', $inc_type);
        $config = getSysConfig($inc_type);
        View::assign('config', $config);

        $link_list = [
            [
                'title' => '管理后台',
                'url' => url('Admin/login')->domain(true)->build() . '?uniacid=' . config('site.uniacid'),
            ],
            [
                'title' => '商家后台',
                // 'url' => url('store://Admin/login')->domain(true)->build() . '?uniacid=' . config('site.uniacid'),
                'url' => Request::domain(true). config('site.cdnurl') . '/index.php/dianpu/dp_login.html?uniacid=' . config('site.uniacid'),
            ],
            [
                'title' => 'h5 地址',
                'url' => Request::domain(true) . config('site.cdnurl') . '/h5/pages/index/index?uniacid=' . config('site.uniacid'),
            ],
        ];
        View::assign('link_list', $link_list);

        return view($inc_type);
    }

    //新增修改配置
    public function handle()
    {
        $param = input('post.');
        $inc_type = $param['inc_type'];
        unset($param['inc_type']);
        getSysConfig($inc_type, $param);
        adminLog("修改商城设置");
        throw new AdminException('操作成功', 1);
    }

    //支付配置
    public function plugin_index()
    {
        // 搜索条件
        $where[] = ['type', '=', 'payment'];
        $list = Plugin::where($where)->select();
        View::assign('list', $list);
        return view();
    }

    //支付配置
    public function plugin_edit()
    {
        $type = input('type');
        $code = input('code');
        $where['type'] = $type;
        $where['code'] = $code;
        $info = Plugin::where($where)->find();
        if (empty($info)) {
            $this->error("插件不存在");
        }

        if ($this->request->isPost()) {
            $config_value = input('config/a');
            $info->config_value = $config_value;
            $info->status = input('status', 0);
            $res = $info->save();
            if ($res) {
                adminLog("修改支付配置");
                throw new AdminException('操作成功', 1);
            } else {
                throw new AdminException('操作失败或没有任何修改');
            }
        }
        View::assign('info', $info);
        View::assign('config_value', $info->config_value);
        return view();
    }

    //所有图标
    public function icons()
    {
        return view();
    }

    //全国地区
    public function region_index()
    {
        $id = input('id');
        $level = input('level');
        $keyword = input('keyword');
        if ($id) {
            $where[] = ['parent_id', '=', $id];
        } else {
            if ($level != '') {
                $where[] = ['level', '=', $level];
            } else {
                $where[] = ['level', '=', 1];
            }
        }
        if ($keyword) {
            $where[] = ['name', 'like', "%$keyword%"];
        }
        $list = Region::where($where)->paginate([
            'query'     => ['keyword' => $keyword, 'level' => $level, 'id' => $id],
            'list_rows' => $this->page_size
        ]);
        // 获取分页显示
        $page = $list->render();
        View::assign('list', $list);
        View::assign('page', $page);
        View::assign('id', $id);
        return view();
    }

    //添加编辑地区
    public function add_edit_region()
    {
        $id = input('id');
        $region = new Region();
        $info = $region->find($id);
        if (IS_POST) {
            $data = input('post.');
            try {
                validate(\app\admin\validate\Region::class)->batch(true)->check($data);
            } catch (ValidateException $e) {
                $error = $e->getError();
                $values = array_values($error);
                throw new AdminException($values[0], 10, ['result' => $error]);
            }
            if ($id) {
                $res = $info->save($data);
            } else {
                $parent_id = input('parent_id', 0);
                $parent_id2 = input('parent_id2');
                $data['parent_id'] = $parent_id2 ? $parent_id2 : $parent_id;
                if ($parent_id2) {
                    $level = 3;
                } elseif ($parent_id) {
                    $level = 2;
                } else {
                    $level = 1;
                }
                $data['level'] = $level;
                $res = $region->save($data);
            }
            if ($res) {
                adminLog($id ? "编辑地区" : "添加地区");
                throw new AdminException('操作成功', 1, ['url' => url('System/region_index', ['id' => $id ? $info['parent_id'] : 0])->build()]);
            } else {
                throw new AdminException('操作失败');
            }
        }
        $arr = [];
        //查出来一级的
        $level1_where[] = ['level', '=', 1];
        $level1_where[] = ['parent_id', '=', 0];
        $parents = Db::name('region')->where($level1_where)->select()->toArray();
        //判断是不是省
        $edit = 0;
        if ($info) {
            if ($info['level'] == 3) {
                $parent_id = $info['parent_id'];
                $parent = Db::name('region')->where('id', $parent_id)->find();
                //查出来二级的
                $level2_where[] = ['level', '=', 2];
                $level2_where[] = ['parent_id', '=', $parent['parent_id']];
                $level2_child = Db::name('region')->where($level2_where)->select()->toArray();
                $arr[0]['sel'] = $parent['parent_id'];
                $arr[0]['child'] = $parents;
                $arr[1]['sel'] = $parent_id;
                $arr[1]['child'] = $level2_child;
            } elseif ($info['level'] == 2) {
                $parent_id = $info['parent_id'];
                //查出来一级的
                $level1_where[] = ['level', '=', 1];
                $level1_where[] = ['parent_id', '=', 0];
                $level1_child = Db::name('region')->where($level1_where)->select()->toArray();
                $arr[0]['sel'] = $parent_id;
                $arr[0]['child'] = $level1_child;
            }
            if ($info['level'] > 1) {
                $edit = 1;
            }
        } else {
            $edit = 1;
        }
        View::assign('info', $info);
        View::assign('arr', $arr);
        View::assign('parents', $parents);
        View::assign('edit', $edit);
        return view();
    }

    //删除地区
    public function region_delete()
    {
        $ids = input('ids/a');
        if (empty($ids)) {
            throw new AdminException('请选择数据');
        }
        $region = new Region();
        $where[] = ['parent_id', 'in', $ids];
        $where[] = ['level', '<', 4];
        $count = $region->where($where)->count();
        if ($count > 0) {
            throw new AdminException('该地区有下级,不允许删除!');
        }
        $res = $region->whereIn('id', $ids)->delete();
        if ($res) {
            throw new AdminException('操作成功', 1);
        } else {
            throw new AdminException('操作失败');
        }
    }

    //运费模板
    public function shipping_index()
    {
        //搜索条件
        $where = [];
        $keyword = input('keyword');
        if ($keyword) {
            $where[] = ['name', 'like', "%$keyword%"];
        }
        $list = Shipping::where($where)->order('id desc')->paginate([
            'query'     => ['keyword' => $keyword],
            'list_rows' => $this->page_size
        ]);
        // 获取分页显示
        $page = $list->render();
        View::assign('list', $list);
        View::assign('page', $page);
        return view();
    }

    //添加编辑运费模板
    public function add_edit_shipping()
    {
        $id = input('id');
        $ship_model = new Shipping();
        $ship_area_model = new ShippingArea();
        $info = $ship_model->find($id);
        if (IS_POST) {
            $data = input('post.');
            try {
                validate(\app\admin\validate\Shipping::class)->batch(true)->check($data);
            } catch (ValidateException $e) {
                $error = $e->getError();
                $values = array_values($error);
                throw new AdminException($values[0], 10, ['result' => $error]);
            }
            $shipping_area_arr = [];
            if ($data['shipping_area']) {
                foreach ($data['shipping_area'] as $shipping_area) {
                    if (empty($shipping_area['area'])) {
                        throw new AdminException('请选择区域');
                    }
                    if (empty($shipping_area['frist_weight'])) {
                        throw new AdminException('请输入首重');
                    }
                    if (empty($shipping_area['frist_money'])) {
                        throw new AdminException('请输入首重运费');
                    }
                    if (empty($shipping_area['second_weight'])) {
                        throw new AdminException('请输入续重');
                    }
                    if (empty($shipping_area['second_money'])) {
                        throw new AdminException('请输入续重运费');
                    }
                }
            }
            if ($id) {
                $res = $info->save($data);
                $sid = $id;
            } else {
                $res = $ship_model->save($data);
                $sid = $ship_model->id;
            }
            if ($data['shipping_area']) {
                foreach ($data['shipping_area'] as $shipping_area) {
                    if (empty($shipping_area['id'])) {
                        unset($shipping_area['id']);
                    }
                    $map = $shipping_area;
                    $map['sid'] = $sid;
                    $shipping_area_arr[] = $map;
                }
                $new_ids = $ship_area_model->saveAll($shipping_area_arr);
                //将没有的删除
                $del_arr = [];
                foreach ($new_ids as $val) {
                    $del_arr[] = $val['id'];
                }
                $ship_area_model->whereNotIn('id', $del_arr)->delete();
            } else {
                $ship_area_model->where('sid', $sid)->delete();
            }
            if ($res) {
                adminLog($id ? "编辑运费模板" : "添加运费模板");
                throw new AdminException('操作成功', 1, ['url' => url('System/shipping_index')->build()]);
            } else {
                throw new AdminException('操作失败');
            }
        }
        $region = Region::where('level<4')->column('id,name,parent_id', 'id');
        $area_list = [];
        if ($id) {
            $area_list = $ship_area_model->where('sid', $id)->select()->each(function ($item) {
                $area_text = Db::name('region')->whereIn('id', $item['area'])->column('name');
                $item['area_text'] = implode(',', $area_text);
                $item['area'] = explode(',', $item['area']);
                return $item;
            })->toArray();
        }
        $tree = getTree($region);
        View::assign('info', $info);
        View::assign('tree', $tree);
        View::assign('area_list', $area_list);
        return view();
    }

    //删除运费模板
    public function shipping_delete()
    {
        $id = input('id');
        if (empty($id)) {
            throw new AdminException('请选择数据');
        }
        $goods = new ConvertGoods();
        $where[] = ['ship_id', '=', $id];
        $count = $goods->where($where)->count();
        if ($count > 0) {
            throw new AdminException('该运费模板有商品使用中,不允许删除!');
        }
        $ship = new Shipping();
        $res = $ship->whereIn('id', $id)->delete();
        if ($res) {
            //删除模板地区
            ShippingArea::where('sid', $id)->delete();
            throw new AdminException('操作成功', 1);
        } else {
            throw new AdminException('操作失败');
        }
    }

    //选择地区
    public function choose_area()
    {
        $id = input('id');
        $area = $area_text = [];
        if ($id) {
            $ship_area_model = new ShippingArea();
            $find = $ship_area_model->find($id);
            $area_text = Db::name('region')->whereIn('id', $find['area'])->column('name');
            $temp_arr = $find['area'];
            $temp_arr = explode(',', $temp_arr);
            foreach ($temp_arr as $val) {
                $area[] = (int)$val;
            }
        }
        $region = Region::where('level<4')->column("id,name,parent_id,'' as actClass", 'id');
        if ($area) {
            $brr = Region::whereIn('id', $area)->column('parent_id');
            if ($brr) {
                $brr = array_flip($brr);
                $brr = array_flip($brr);
                $brr = array_values($brr);
                foreach ($region as $key => $v) {
                    if ($v['parent_id'] == 0 && in_array($v['id'], $brr)) {
                        $region[$key]['actClass'] = 'parentAct';
                    }
                }
            }
        }
        $tree = getTree($region);
        View::assign('tree', $tree);
        View::assign('area', $area);
        View::assign('area_text', $area_text);
        return view();
    }

    //清空系统缓存
    public function cleanCache()
    {
        $runtimepath = runtime_path();
        delDir($runtimepath);
        Cache::clear();
        $this->success("清除成功");
    }

    public function tabBarList(): \think\response\View
    {
        $keyword = $this->request->param('keyword');

        $list = TabBar::when($keyword, function (Query $query, $keyword) {
            $query->whereLike('name', "%$keyword%");
        })->order('id', 'desc')->paginate([
            'query'     => ['keyword' => $keyword],
            'list_rows' => $this->page_size
        ]);

        $page = $list->render();

        View::assign('list', $list);
        View::assign('page', $page);
        return view();
    }

    public function tabBarDetail()
    {
        $id = $this->request->param('id');

        $info = TabBar::find($id);

        if ($this->request->isPost()) {
            if ($id) {
                $info->setAttrs($this->request->param());
                $info->save();
            } else {
                TabBar::create($this->request->param());
            }

            return redirect(url("System/TabBarList"));
        }

        View::assign('info', $info);
        View::assign('pages', Page::MAP);
        return \view();
    }

    public function tabBarDel($id)
    {
        $id = $this->request->param('id');

        $tabbar = TabBar::find($id);

        $tabbar->delete();

        $this->success('删除成功');
    }

    public function distribution()
    {
        $distributionConfig = Config::where('name', 'distribution')->findOrEmpty();

        View::assign('info', $distributionConfig ? json_decode($distributionConfig->value, true) : '');

        return \view();
    }

    public function save_distribution()
    {
        $distributionConfig = Config::where('name', 'distribution')->findOrEmpty();

        $distributionConfig->name = 'distribution';
        $distributionConfig->value = json_encode($this->request->post());
        $distributionConfig->save();

        $this->success('保存成功');
    }
}
